<?php
namespace Register\model;

 use Zend\Db\ResultSet\ResultSet;
 use Zend\Db\TableGateway\TableGateway;
 use Zend\Db\Sql\Select;
 use Zend\Paginator\Adapter\DbSelect;
 use Zend\Paginator\Paginator;

class ParticipantEmailTable
{
    protected $tableGateway;
    
    function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway=$tableGateway;
    }
    
    public function fetchAll($paginated=false)
    {
        if ($paginated) {
            // create a new Select object for the table album
            $select = new Select('participant_email');
            // create a new result set based on the Album entity
            $resultSetPrototype = new ResultSet();
            $resultSetPrototype->setArrayObjectPrototype(new ParticipantEmail());
            // create a new pagination adapter object
            $paginatorAdapter = new DbSelect(
                // our configured select object
                $select,
                // the adapter to run it against
                $this->tableGateway->getAdapter(),
                // the result set to hydrate
                $resultSetPrototype
            );
            $paginator = new Paginator($paginatorAdapter);
            return $paginator;
        }
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }
    
    public function getParticipantEmail($id)
    {
        $rowset = $this->tableGateway->select(array('ID' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }
    
    public function saveParticipantEmail(ParticipantEmail $participant,$type)
    {
        $data = array(
               'ID' => $participant->ID,
               'Email' => $participant->EMAIL
        );
        $id = $participant->ID;
        if ($type==0) {
            $this->tableGateway->insert($data);
        } elseif($type==1) {
            if ($this->getparticipantEmail($id)) {
                $this->tableGateway->update($data, array('ID' => $id));
            } else {
                throw new \Exception('Participant ID does not exist');
            }
        }
    }
}

?>